﻿using System;
using System.Collections.Generic;
using System.Linq;
using Gumini.JulaDB.DataTypes;
using Gumini.JulaDB.Expressions.Operators;

namespace Gumini.JulaDB.Expressions
{
    /// <summary>
    /// A node in the expression tree that has one child node and an unary operator.
    /// </summary>
    internal class UnaryExpression : Expression
    {
        public UnaryExpression(string op, Expression child)
            : base(child)
        {
            this.Operator = OperatorFactory.GetUnaryOperator(op);
        }

        public UnaryOperator Operator { get; private set; }

        public Expression Child
        {
            get { return base._children[0]; }
        }
        
        public override DataType InferType(Context<DataType> context)
        {
            var childType = this.Child.InferType(context);
            return Operator.GetReturnType();
        }

        public override bool Equals(Expression other)
        {
            var b = other as UnaryExpression;
            if (b == null)
                return false;
            return
                this.Operator == b.Operator &&
                this.Child.Equals(b.Child);
        }

        public override TypedValue Evaluate(List<Context<TypedValue>> context)
        {
            var childResult = this.Child.Evaluate(context);
            return this.Operator.Evaluate(childResult);
        }

        public override string ToString()
        {
            return String.Format("({0} {1})", this.Operator.Names.First(), this.Child);
        }
    }
}
